package com.ssm.sport.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ssm.sport.dto.ResultDTO;
import com.ssm.sport.entity.Cart;
import com.ssm.sport.entity.Category;
import com.ssm.sport.entity.Product;
import com.ssm.sport.entity.User;
import com.ssm.sport.entity.Shipping;
import com.ssm.sport.service.CartService;
import com.ssm.sport.service.CategoryService;
import com.ssm.sport.service.ProductService;
import com.ssm.sport.service.ShippingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ssm.sport.vo.CartVO;
import org.springframework.util.CollectionUtils;

/**
 * 购物车控制器
 */
@Controller
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    @Autowired
    private ProductService productService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ShippingService shippingService;

    /**
     * 购物车页面
     */
    @GetMapping("")
    public String cart(Model model, HttpSession session, HttpServletResponse response) {
        // 设置响应头
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "0");

        // 获取所有一级分类，用于导航栏
        List<Category> categories = categoryService.getTopCategories();
        model.addAttribute("categories", categories);

        // 获取当前登录用户
        User user = (User) session.getAttribute("user");
        if (user == null) {
            // 未登录，跳转到登录页面
            return "redirect:/login";
        }

        try {
            // 获取购物车列表
            List<Map<String, Object>> cartList = cartService.getCartList(user.getId());
            for (Map<String, Object> map : cartList) {
                String productImage = (String) map.get("productImage");
                productImage="/sport_mall_war"+productImage;
                map.put("productImage", productImage);
            }
            model.addAttribute("cartList", cartList);

            // 计算总价
            double totalPrice = cartList.stream()
                    .filter(item -> (Integer)item.get("checked") == 1)
                    .mapToDouble(item -> Double.parseDouble(item.get("productTotalPrice").toString()))
                    .sum();
            model.addAttribute("totalPrice", totalPrice);
            
            // 添加推荐商品
            List<Integer> cartProductIds = cartList.stream()
                    .map(item -> (Integer)item.get("productId"))
                    .collect(Collectors.toList());
            
            // 获取热门商品作为推荐
            List<Product> hotProducts = productService.getHotProducts(8);
            // 过滤掉已经在购物车中的商品
            List<Product> recommendProducts = hotProducts.stream()
                    .filter(product -> !cartProductIds.contains(product.getId()))
                    .limit(4)
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(recommendProducts)) {
                for (Product recommendProduct : recommendProducts) {
                    recommendProduct.setMainImage("/sport_mall_war"+recommendProduct.getMainImage());
                }
            }
            model.addAttribute("recommendProducts", recommendProducts);

            // 获取收货地址列表
            List<Shipping> shippingAddresses = shippingService.getByUserId(user.getId());
            model.addAttribute("shippingAddresses", shippingAddresses);

            return "cart";
        } catch (Exception e) {
            // 记录错误日志
            e.printStackTrace();
            model.addAttribute("error", "加载购物车数据时发生错误");
            return "error/500";
        }
    }

    /**
     * 添加商品到购物车
     */
    @PostMapping("/add")
    @ResponseBody
    public ResultDTO<?> addToCart(Integer productId, Integer quantity, HttpSession session, HttpServletResponse response) {
        // 设置响应头
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        
        if (productId == null || productId <= 0) {
            return ResultDTO.failure("商品ID不合法");
        }

        if (quantity == null || quantity <= 0) {
            quantity = 1; // 默认数量为1
        }

        // 获取当前登录用户
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return ResultDTO.failure("请先登录");
        }

        try {
            // 检查商品是否存在
            Product product = productService.getById(productId);
            if (product == null || product.getStatus() != 1) {
                return ResultDTO.failure("商品不存在或已下架");
            }

            // 检查库存
            if (product.getStock() < quantity) {
                return ResultDTO.failure("商品库存不足");
            }

            // 检查购物车中是否已存在该商品
            QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", user.getId())
                    .eq("product_id", productId);
            Cart existCart = cartService.getOne(queryWrapper);

            if (existCart != null) {
                // 已存在，更新数量
                existCart.setQuantity(existCart.getQuantity() + quantity);
                cartService.updateById(existCart);
            } else {
                // 不存在，新增购物车项
                Cart cart = new Cart();
                cart.setUserId(user.getId());
                cart.setProductId(productId);
                cart.setQuantity(quantity);
                cart.setChecked(1); // 默认选中
                cartService.save(cart);
            }

            return ResultDTO.success(null, "成功加入购物车");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultDTO.failure("添加到购物车失败，请稍后重试");
        }
    }

    /**
     * 更新购物车商品数量
     */
    @PostMapping("/update")
    @ResponseBody
    public ResultDTO<?> updateCart(Integer id, Integer quantity, HttpSession session) {
        if (id == null || id <= 0) {
            return ResultDTO.failure("参数错误");
        }

        if (quantity == null || quantity <= 0) {
            return ResultDTO.failure("数量必须大于0");
        }

        // 获取当前登录用户
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return ResultDTO.failure("请先登录");
        }

        // 获取购物车项
        Cart cart = cartService.getById(id);
        if (cart == null || !cart.getUserId().equals(user.getId())) {
            return ResultDTO.failure("购物车项不存在");
        }

        // 检查库存
        Product product = productService.getById(cart.getProductId());
        if (product.getStock() < quantity) {
            return ResultDTO.failure("商品库存不足");
        }

        // 更新数量
        cart.setQuantity(quantity);
        cartService.updateById(cart);

        return ResultDTO.success(null, "更新成功");
    }

    /**
     * 删除购物车商品
     */
    @PostMapping("/delete")
    @ResponseBody
    public ResultDTO<?> deleteCart(Integer id, HttpSession session) {
        if (id == null || id <= 0) {
            return ResultDTO.failure("参数错误");
        }

        // 获取当前登录用户
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return ResultDTO.failure("请先登录");
        }

        // 获取购物车项
        Cart cart = cartService.getById(id);
        if (cart == null || !cart.getUserId().equals(user.getId())) {
            return ResultDTO.failure("购物车项不存在");
        }

        // 删除购物车项
        cartService.removeById(id);

        return ResultDTO.success(null, "删除成功");
    }

    /**
     * 更新选中状态
     */
    @PostMapping("/select")
    @ResponseBody
    public ResultDTO<?> selectCart(Integer id, Integer checked, HttpSession session) {
        if (id == null || id <= 0) {
            return ResultDTO.failure("参数错误");
        }

        if (checked == null || (checked != 0 && checked != 1)) {
            return ResultDTO.failure("参数错误");
        }

        // 获取当前登录用户
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return ResultDTO.failure("请先登录");
        }

        // 获取购物车项
        Cart cart = cartService.getById(id);
        if (cart == null || !cart.getUserId().equals(user.getId())) {
            return ResultDTO.failure("购物车项不存在");
        }

        // 更新选中状态
        cart.setChecked(checked);
        cartService.updateById(cart);

        return ResultDTO.success(null, "更新成功");
    }

    /**
     * 全选/取消全选
     */
    @PostMapping("/select-all")
    @ResponseBody
    public ResultDTO<?> selectAllCart(Integer checked, HttpSession session) {
        if (checked == null || (checked != 0 && checked != 1)) {
            return ResultDTO.failure("参数错误");
        }

        // 获取当前登录用户
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return ResultDTO.failure("请先登录");
        }

        // 更新所有购物车项的选中状态
        cartService.updateCheckedByUserId(user.getId(), checked);

        return ResultDTO.success(null, "更新成功");
    }

    /**
     * 显示简化版结算页面（用于解决订单提交问题）
     */
    @GetMapping("/checkout-simple")
    public String showSimpleCheckout(HttpSession session, Model model) {
        // 1. 检查用户是否登录
        Object userObj = session.getAttribute("user");
        if (userObj == null) {
            return "redirect:/login";
        }
        
        Integer userId = ((com.ssm.sport.entity.User) userObj).getId();
        
        // 2. 获取用户购物车中已勾选的商品
        List<CartVO> checkedCartItems = cartService.getCheckedCartItems(userId);
        
        if (checkedCartItems == null || checkedCartItems.isEmpty()) {
            return "redirect:/cart?error=请先选择商品";
        }
        
        // 3. 计算总价
        BigDecimal totalPrice = new BigDecimal("0");
        for (CartVO cartItem : checkedCartItems) {
            totalPrice = totalPrice.add(cartItem.getProductTotalPrice());
        }
        
        // 4. 获取用户的收货地址
        List<Shipping> shippingAddresses = shippingService.getByUserId(userId);
        
        // 5. 将数据传递给视图
        model.addAttribute("cartItems", checkedCartItems);
        model.addAttribute("totalPrice", totalPrice);
        model.addAttribute("shippingAddresses", shippingAddresses);
        
        System.out.println("进入简化版结算页面，已选商品数量: " + checkedCartItems.size() + ", 总价: " + totalPrice);
        
        return "checkout_simple";
    }

    /**
     * 进入结算页面
     */
    @GetMapping("/checkout")
    public String checkout(HttpSession session, Model model) {
        // 从session中获取用户ID
        Object userObj = session.getAttribute("user");
        if (userObj == null) {
            return "redirect:/login";
        }
        
        Integer userId = ((com.ssm.sport.entity.User) userObj).getId();
        
        // 获取购物车中已勾选的商品列表
        List<CartVO> cartItems = cartService.getCheckedCartItems(userId);
        if (CollectionUtils.isEmpty(cartItems)) {
            return "redirect:/cart?error=Please+select+items+first";
        }
        
        // 计算总价
        BigDecimal totalPrice = BigDecimal.ZERO;
        for (CartVO item : cartItems) {
            totalPrice = totalPrice.add(item.getProductTotalPrice());
        }
        
        // 获取用户的收货地址列表
        List<Shipping> shippingAddresses = shippingService.getByUserId(userId);
        
        // 传递数据到视图
        model.addAttribute("cartItems", cartItems);
        model.addAttribute("totalPrice", totalPrice);
        model.addAttribute("shippingAddresses", shippingAddresses);
        
        return "checkout";
    }
} 